import Vue from 'vue'
import Vuex from 'vuex'
import components from './components'

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    user: null,
    activiting: 'userManager',
    activeTabs: [components['userManager']],
    menus: [
      {
        title: '系统管理',
        name: 'xtgl',
        children: [
          {
            title: '用户管理',
            name: 'userManager'
          },
          {
            title: '角色管理',
            name: 'roleManager'
          }
        ]
      },
      {
        title: '表单元素',
        name: 'form',
        children: [
          {
            title: '穿梭框',
            name: 'eotransfer'
          },
          {
            title: '弹出框',
            name: 'alerttest'
          }
        ]
      }
    ]
  },
  mutations: {
    removeTab (state, name) {
      // 定义变量寻找删除的索引
      let index = -1
      // 寻找删除的索引
      for (let i = 0; i < state.activeTabs.length; i++) {
        if (state.activeTabs[i].name === name) {
          index = i
          break
        }
      }
      // 将删除的从数组中去掉
      state.activeTabs.splice(index, 1)
      // 如果数组中还有元素
      if (state.activeTabs.length) {
        // 如果索引等于数组长度则说明删除的是最后一个菜单，将索引前移一位
        if (index > state.activeTabs.length - 1) {
          index--
        }
        // 改变当前选中tab页为计算后的tab页面
        state.activiting = state.activeTabs[index].name
      } else {
        // 否则置空
        state.activiting = ''
      }
    },
    changeActivite (state, value) {
      // 改变当前选中的值
      state.activiting = value
    },
    addTab (state, name) {
      // 过滤名字为传入名字的tab
      let f = state.activeTabs.filter(e => e.name == name)
      // 如果已经添加到活动的tab数组中了则只改变当前活动tab的name，否则向活动tab数组中添加该组件
      if (!f.length) {
        state.activeTabs.push(components[name])
      }
      // 如果组件名称合法则改变当前活动tab的name为传入的name
      if (components[name]) {
        state.activiting = name
      }
    },
    setUser (state, value) {
      state.user = value
    }
  }
})

export default store
